package kr.hkit.wordnote.fragment;

import java.util.ArrayList;
import java.util.Locale;

import kr.hkit.wordnote.activity.MainActivity;
import kr.hkit.wordnote.db.WordDBHelper;
import kr.hkit.wordnote.exception.DBException;
import kr.hkit.wordnote.fragment.WordInputFragment.OnWordChangedListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.example.wordnote2.R;

public class WordListFragment extends Fragment {
	OnWordChangedListener mHost;
	OnEditButtonClickedListener mHost2;
	ListView list;
	
	public static WordListFragment newInstance(ArrayList<String> engList, 
			ArrayList<String> korList) {
		WordListFragment frag = new WordListFragment();
		Bundle args = new Bundle();
		args.putSerializable("engList", engList);
		args.putSerializable("korList", korList);
		
		frag.setArguments(args);

		return frag;
	}
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try{
			mHost = (OnWordChangedListener)activity;
			mHost2 = (OnEditButtonClickedListener)activity;
		}catch(ClassCastException e){
			throw new ClassCastException("액티비티는 OnWirdChanged와 onButtonClicked를 구현해야합니다.");
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		LinearLayout linear = (LinearLayout) inflater.inflate(R.layout.wordlistfragment, container, false);

		final ArrayList<String> engList = (ArrayList<String>) getArguments().get("engList");
		final ArrayList<String> korList = (ArrayList<String>) getArguments().get("korList");
		list = (ListView) linear.findViewById(R.id.list);
		
		//어댑터를 만들어 리스트 뷰에 항목을 추가하는 메소드
		makeList(engList);
		
		//항목을 클릭 했을 때, 단어 뜻을 보여주는 대화상자를 띄운다.
		list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				final int pos = position;
				new AlertDialog.Builder(getActivity())
				.setTitle(engList.get(position))
				.setMessage(korList.get(position))
				.setPositiveButton("확인", null)
				.setNegativeButton("예문", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						String word = engList.get(pos); 
						Intent intent = new Intent(Intent.ACTION_VIEW, 
								Uri.parse("http://m.endic.naver.com/search.nhn?query="+
										word+"&searchOption=example"));
						startActivity(intent);
						
					}
				})
				.show();
			}
		});
		
		//항목을 롱클릭 했을 때, 편집 및 삭제 등을 할 수 있는 대화상자를 띄운다. 
		list.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				final int pos = position;
				new AlertDialog.Builder(getActivity())
				.setTitle(engList.get(position))
				.setPositiveButton("삭제", new DialogInterface.OnClickListener(){
					public void onClick(DialogInterface dialog, int which) {
						WordDBHelper helper = null;
						try {
							helper = new WordDBHelper(getActivity());
							helper.deleteWord(engList.get(pos));
							engList.remove(pos);
							korList.remove(pos);
							//제거가 되면 리스트 뷰의 항목을 갱신한다. 
							makeList(engList);
							//단어가 삭제 되었음을 액티비티에 알린다.
							mHost.onWordChanged();
							Toast.makeText(getActivity(), "삭제완료", 0).show();
						} catch (DBException e) {
							Toast.makeText(getActivity(), e.getMessage(), 0).show();
						} finally {
							helper.close();
						}
					}
				})
				.setNeutralButton("편집", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						String eng = engList.get(pos);
						String kor = engList.get(pos);
						mHost2.onEditButtonClicked(engList.get(pos), korList.get(pos));
						
					}
				})
				.show();
				return true;
			}
		});

		return linear;
	}
	
	
	//리스트뷰에 항목을 추가하는 메소드
	public void makeList(ArrayList<String> engList){
		//어댑터를 만들고 인수로 문자열을 나타낼 수 있는 레이아웃과 engList를 인수로 전달한다. 
		ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, engList);
		list.setAdapter(adapter);
	}
	
	public interface OnEditButtonClickedListener{
		public void onEditButtonClicked(String eng, String kor);
	}
}
